package com.tangtang.basic.threads.feture;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class FutureDemo2 {
    public static void main(String[] args) throws InterruptedException, ExecutionException {
        ExecutorService executor = Executors.newCachedThreadPool();
        Callable<String> callable = new Callable<String>() {
            @Override
            public String call() throws Exception {
                Thread.sleep(10000);
                return "hello world";
            }
        };

        Future<String> delegate = executor.submit(callable);
        executor.shutdown();
        Future<String> wrapper = new Future<String>() {
            @Override
            public boolean cancel(boolean mayInterruptIfRunning) {
                return !delegate.isCancelled();
            }

            @Override
            public boolean isCancelled() {
                return delegate.isCancelled();
            }

            @Override
            public boolean isDone() {
                return delegate.isDone();
            }

            @Override
            public String get() throws InterruptedException, ExecutionException {
                return delegate.get();
            }

            @Override
            public String get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
                return delegate.get(timeout, unit);
            }
        };
        System.out.println(wrapper.get());
    }

}
